
#include "download.h"
#include "system_info.h"
#include "board.h"
#include "settings.h"
#include "SD_MMC.h"

#include <esp_log.h>
#include <cstring>
#include <vector>
#include <sstream>
#include <algorithm>

#define TAG "Download"

#define PIC1_PATH "/sdcard/pic1.jpg"
#ifdef __cplusplus
extern "C" {
#endif 
int down_pic_from_server(const char* url,const char* md5,const char* storage_path)
{
    //SD_Init();
    vTaskDelay(pdMS_TO_TICKS(6000));
    ESP_LOGI(TAG, "Upgrading firmware from %s", url);

    auto http = Board::GetInstance().CreateHttp();
    if (!http->Open("GET", url)) {
        ESP_LOGE(TAG, "Failed to open HTTP connection");
        delete http;
        return 1000;
    }

    size_t content_length = http->GetBodyLength();
    if (content_length == 0) {
        ESP_LOGE(TAG, "Failed to get content length");
        delete http;
        return 1000;
    }
    ESP_LOGI(TAG,"http file size:%d\n ",content_length);
    char buffer[5120];
    size_t total_read = 0, recent_read = 0;
    auto last_calc_time = esp_timer_get_time();

    FILE *f = fopen(PIC1_PATH, "wb");
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open file for writing");
        return ESP_FAIL;
    }
    ESP_LOGI(TAG, "File written");


    while (true) {
        int ret = http->Read(buffer, sizeof(buffer));
        if (ret < 0) {
            ESP_LOGE(TAG, "Failed to read HTTP data: %s", esp_err_to_name(ret));
            delete http;
            return 1000;
        }
        int writeret = fwrite(buffer,ret,1,f);
        ESP_LOGI(TAG,"fwrite :%d\n",writeret);
        // Calculate speed and progress every second
        recent_read += ret;
        total_read += ret;
        if (esp_timer_get_time() - last_calc_time >= 1000000 || ret == 0) {
            size_t progress = total_read * 100 / content_length;
            ESP_LOGI(TAG, "Progress: %zu%% (%zu/%zu), Speed: %zuB/s", progress, total_read, content_length, recent_read);
            //if (upgrade_callback_) {
            //    upgrade_callback_(progress, recent_read);
            //}
            last_calc_time = esp_timer_get_time();
            recent_read = 0;
        }

        if (ret == 0) {
            break;
        }
        //fprintf(f, buffer);
    }
    delete http;
    fclose(f);
    ESP_LOGI(TAG, "download  successful, %s\n",url);
    sd_get_file_size(PIC1_PATH);
    return 0;
}



#ifdef __cplusplus
}
#endif 